include(FetchContent)

set(ESPRESSO_NAME espresso)
set(ESPRESSO_URL https://github.com/crarch/espresso)
SET(ESPRESSO_SOURCE_DIR ${PROJECT_SOURCE_DIR}/download/${ESPRESSO_NAME})

include(FetchContent)
FetchContent_Declare(${ESPRESSO_NAME}
        GIT_REPOSITORY ${ESPRESSO_URL}
        GIT_TAG 4a866081dcb94a8cdf3627d6f943739651678234
        SOURCE_DIR ${ESPRESSO_SOURCE_DIR})
# 有的话就不再下载了
if (NOT EXISTS ${ESPRESSO_SOURCE_DIR})
    FetchContent_GetProperties(${ESPRESSO_NAME})
    if (NOT ${ESPRESSO_NAME}_POPULATED)
        message(STATUS "Downloading ${ESPRESSO_NAME} from ${ESPRESSO_URL}")
        FetchContent_Populate(${ESPRESSO_NAME})
    endif ()
endif ()

#set(BUILD_DOC OFF)
#FetchContent_MakeAvailable(${ESPRESSO_NAME})
#add_subdirectory(${ESPRESSO_SOURCE_DIR})

# make espresso first for verilog generation
set(ESPRESSO_BUILD_DIR ${CMAKE_BINARY_DIR}/${ESPRESSO_NAME})
message(STATUS "${CMAKE_COMMAND} -S ${ESPRESSO_SOURCE_DIR} -B ${ESPRESSO_BUILD_DIR} -G ${CMAKE_GENERATOR} -D BUILD_DOC=OFF")
execute_process(COMMAND ${CMAKE_COMMAND} -S ${ESPRESSO_SOURCE_DIR} -B ${ESPRESSO_BUILD_DIR} -G ${CMAKE_GENERATOR} -D BUILD_DOC=OFF
        WORKING_DIRECTORY ${ESPRESSO_SOURCE_DIR}
        RESULT_VARIABLE CONFIGURE_RESULT)
if (NOT CONFIGURE_RESULT EQUAL 0)
    message(FATAL_ERROR "Failed when configuring ${ESPRESSO_NAME} CMake")
endif ()
message(STATUS "${CMAKE_COMMAND} --build ${ESPRESSO_BUILD_DIR} -j")
execute_process(COMMAND ${CMAKE_COMMAND} --build ${ESPRESSO_BUILD_DIR} -j
        WORKING_DIRECTORY ${ESPRESSO_SOURCE_DIR}
        RESULT_VARIABLE BUILD_RESULT)
if (NOT BUILD_RESULT EQUAL 0)
    message(FATAL_ERROR "Failed when building ${ESPRESSO_NAME} CMake")
endif ()
message(STATUS "${CMAKE_COMMAND} --install ${ESPRESSO_BUILD_DIR} --prefix=${CMAKE_SOURCE_DIR}")
execute_process(COMMAND ${CMAKE_COMMAND} --install ${ESPRESSO_BUILD_DIR} --prefix=${ESPRESSO_BUILD_DIR}
        WORKING_DIRECTORY ${ESPRESSO_SOURCE_DIR}
        RESULT_VARIABLE INSTALL_RESULT)
if (NOT INSTALL_RESULT EQUAL 0)
    message(FATAL_ERROR "Failed when installing ${ESPRESSO_NAME} CMake")
endif ()
file(GLOB_RECURSE ESPRESSO_BINARY "${ESPRESSO_BUILD_DIR}/bin/*")
message(STATUS "espresso binary: ${ESPRESSO_BINARY}")
if (WIN32)
    set(ESPRESSO_SUFFIX .exe)
else ()
    set(ESPRESSO_SUFFIX)
endif ()

file(COPY_FILE ${ESPRESSO_BINARY} ${CMAKE_SOURCE_DIR}/espresso${ESPRESSO_SUFFIX})
if (NOT WIN32)
    file(MAKE_DIRECTORY "$ENV{HOME}/.local/bin")
    file(COPY_FILE ${ESPRESSO_BINARY} "$ENV{HOME}/.local/bin/espresso${ESPRESSO_SUFFIX}")
endif ()
if (EXISTS ${CMAKE_SOURCE_DIR}/.bloop)
    file(COPY_FILE ${ESPRESSO_BINARY} ${CMAKE_SOURCE_DIR}/.bloop/espresso${ESPRESSO_SUFFIX})
endif ()

